<template >
  <el-dialog
    :append-to-body="true"
    :before-close="cancel"
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="boxDialogVisible"
    class="tree-dialog-form scrollbar selectBox"
    heihgt="607px"
    width="686px"
  >
    <div class="box">
      <div class="left-box">
        <div class="left-top">
          <el-input
            :placeholder="searchConfig.title?searchConfig.title:'请输入'"
            @focus="onclick"
            @input="leftInputChange"
            @keyup.enter.native="enter(searchConfig.params[searchConfig.key])"
            class="vc-search-input"
            size="small"
            suffix-icon="el-icon-search select-box-search"
            v-if="searchConfig.show===false?false:true"
            v-model="searchConfig.params[searchConfig.key]"
          ></el-input>
        </div>
        <div class="left-bottom">
          <el-tabs ref="selectTab" v-model="selectBox.tabConfig.activeName">
            <el-tab-pane
              :key="idx"
              :label="item.title"
              :name="item.name"
              style="height:100%"
              v-for="(item,idx) in selectBox.tabConfig.items"
            >
              <div style="height: 93%">
                <el-form class="personnel-form-top" label-width="90px" size="small">
                  <div
                    class="vc-page vc-page-parts"
                    style="position:relative;overflow:hidden;padding-bottom:20px; margin-right: 0px;"
                  >
                    <!-- 左侧 - 用户组树 -->
                    <div class="tree-dialog scrollbar" style="width:600px;background: white;">
                      <el-tree
                        :data="item.treeConfig.insideTreeData"
                        :default-expanded-keys="item.treeConfig.expandedKeys"
                        :empty-text="item.treeConfig.treeEmptyText"
                        :expand-on-click-node="true"
                        :key="treeKey"
                        :props="item.defaultProps"
                        :ref="'roleTree'"
                        :render-content="renderContent"
                        @check-change="item.treeConfig.handleSelectionChange"
                        check-strictly
                        class="org-tree"
                        highlight-current
                        node-key="id"
                        render-after-expand
                        show-checkbox
                        v-if="!showList && listStyle ==='tree'&&indep"
                      ></el-tree>
                      <el-tree
                        :data="item.treeConfig.insideTreeData"
                        :default-expanded-keys="item.treeConfig.expandedKeys"
                        :empty-text="item.treeConfig.treeEmptyText"
                        :expand-on-click-node="true"
                        :key="treeKey"
                        :props="item.defaultProps"
                        :ref="'roleTree'"
                        :render-content="renderContent"
                        @check-change="item.treeConfig.handleSelectionChange"
                        class="org-tree"
                        highlight-current
                        node-key="id"
                        render-after-expand
                        show-checkbox
                        v-if="!showList && listStyle ==='tree'&&!indep"
                      ></el-tree>
                      <el-checkbox-group
                        class="checkbox"
                        v-else-if="showList&& leftList.items.length!==0"
                        v-model="leftList.default"
                      >
                        <div :key="idx" class="checkBox-box" v-for="(item,idx) in leftList.items">
                          <div class="vm-line icon-left">
                            <el-checkbox
                              :label="item.id"
                              @change="checked=>leftListChange(checked,item)"
                            >
                              <i class="el-icon-user checkedIcon" style="color:rgba(170,207,255,1)"></i>
                              <span>{{item[searchConfig.key]}}</span>
                            </el-checkbox>
                          </div>
                        </div>
                      </el-checkbox-group>
                      <div
                        style="text-align: center;"
                        v-else-if="showList && leftList.items.length===0"
                      >暂无数据</div>
                    </div>
                  </div>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div class="right-box" style="float:right;height:100%">
        <div class="right-top">
          <div class="top-box">
            <span>已选择&nbsp;{{ rightList.items.length ? `(${rightList.items.length})` : '' }}</span>
            <span @click="removeCheck" class="color-primary" style="cursor: pointer;">清空</span>
          </div>
        </div>
        <div class="right-bottom scrollbar">
          <ul class="checkbox">
            <li
              :key="idx"
              class="checkBox-box"
              v-for="(item,idx) in rightList.items"
              v-show="item.type !== iconConfig.parentType.key"
            >
              <i :class="iconConfig.childrenType.icon"></i>
              <span class="valueBox">{{ item[rightKey] || item[rightKeyQ] }}</span>
              <div class="vm-line icon-right">
                <i class="el-icon-circle-close" style="color:#DFE7F1" v-on:click="clickIcon(item)"></i>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div class="dialog-footer" style="text-align: right;padding:20px">
      <el-button @click="cancel" size="small">取消</el-button>
      <el-button :disabled="disabled" @click="save" size="small" type="primary">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'SelectBox',
  components: {},
  props: {
    title: '',
    searchConfig: {
      type: Object,
      default () {
        return {
          title: '请输入',
          patch: '',
          show: true,
          key: 'username',
          params: {}
        }
      }
    },
    rightKey: {
      type: String,
      default () {
        return 'text'
      }
    },
    rightKeyQ: '',
    boxDialogVisible: {
      type: Boolean,
      default () {
        return false
      }
    },
    checkedNode: {
      type: Array,
      default () {
        return []
      }
    },
    allNode: {
      type: Array,
      default () {
        return []
      }
    },
    listStyle: {
      type: String,
      default () {
        return 'tree'
      }
    },
    defaultProps: {
      type: Object,
      default () {
        return {
          id: 'id',
          label: 'text',
          children: 'children',
          isLeaf: 'isLeaf'
        }
      }
    },
    iconConfig: {
      type: Object,
      default () {
        return {
          parentType: {
            key: 'rgroup',
            icon: 'vc-icon vc-icon-tree-rGroup'
          },
          childrenType: {
            key: 'permission',
            icon: 'vc-icon vc-icon-tree-role'
          }
        }
      }
    },
    tabTitle: {
      type: String,
      default () {
        return '用户组织机构'
      }
    },
    indep: false
  },
  data () {
    return {
      defaultPer: {
        disabled: data => {
          if (
            data.type === this.iconConfig.parentType.key &&
            data.children.length === 0
          ) {
            return true
          }
        }
      },
      disabled: false,
      showList: false,
      treeKey: '1',
      insideAllNode: [],
      insideChecked: [],
      checkList: [],
      timer: '',
      para_rds_ud: {
        roleIds: [],

        ugroupId: ''
      },
      roleData: [],
      roleTreeData: [],
      expandedKeys: [],
      treeEmptyText: ' ',
      // 索引值
      index: 0,
      // insideTreeData
      insideTreeData: [],
      selectBox: {
        searchConfig: {
          // 搜索
          placeholder: '请输入', // 默认提示
          key: 'key' // key值
        },
        tabConfig: {
          activeName: 'org', // 默认tab页
          index: 0,
          items: [
            {
              name: 'org',
              title: '用户组织机构',
              defaultProps: {
                id: 'id',
                label: 'text',
                children: 'children',
                isLeaf: 'isLeaf'
              },
              treeConfig: {
                insideTreeData: [],
                expandedKeys: [],
                treeEmptyText: ' ',
                handleSelectionChange: this.handleSelectionChange
              }
            }
          ]
        }
      },
      // 最后提交
      addList: [],
      deleteList: [],
      // 右侧多选列表
      rightList: {
        items: [],
        default: []
      },
      // 右侧多选列表
      leftList: {
        items: [],
        default: []
      }
    }
  },
  computed: {
    id () {
      return this.$parent.id // id指打开对话框之前父页面所选择的用户组id.
    }
  },
  mounted () {},
  created () {},

  watch: {
    boxDialogVisible (value) {
      if (value) {
        this.init()
        this.disabled = false
      }
    }
  },

  methods: {
    /*
    leftInputChange
    */
    leftInputChange (value) {
      if (this.listStyle === 'tree' && value.length === 0) {
        this.showList = false
        this.$nextTick(() => {
          this.$refs.roleTree[this.index].setCheckedKeys(this.leftList.default)
        })
      }
    },
    /*

    */
    onclick () {
      const search = document.getElementsByClassName('select-box-search')[0]
      search.onclick = () => {
        let flage = true
        Object.keys(this.searchConfig.params).forEach(i => {
          this.searchConfig.params[i] = this.searchConfig.params[i].trim()
          if (this.searchConfig.params[i] === '') {
            flage = false
          }
        })
        if (flage) {
          this.$api[this.searchConfig.patch]({
            data: this.searchConfig.params
          }).then(res => {
            this.leftList.items = res.data
            this.showList = true
          })
        }
      }
    },
    /*
      回车
    */
    enter (value) {
      let flage = true
      Object.keys(this.searchConfig.params).forEach(i => {
        this.searchConfig.params[i] = this.searchConfig.params[i].trim()
        if (this.searchConfig.params[i] === '') {
          flage = false
        }
      })
      if (flage) {
        this.$api[this.searchConfig.patch]({
          data: this.searchConfig.params
        }).then(res => {
          this.leftList.items = res.data
          this.showList = true
        })
      }
    },
    /*
      初始化结构
    */
    init () {
      if (this.$refs.roleTree && this.$refs.roleTree[0]) {
        this.$refs.roleTree[0].setCheckedKeys([])
      }
      this.rightList.items = []
      this.selectBox.tabConfig.items[this.index].treeConfig.insideTreeData = []
      this.insideChecked = []
      this.insideAllNode = []
      this.selectBox.tabConfig.items[0].title = this.tabTitle
        ? this.tabTitle
        : '用户组织机构'
      this.insideAllNode = [...this.allNode]
      this.insideChecked = [...this.checkedNode]
      this.leftList.default = this.insideChecked.map(i => i.id)
      if (this.listStyle === 'tree') {
        this.initTree(this.insideAllNode, this.insideChecked)
      } else {
        this.initList(this.insideAllNode, this.insideChecked)
      }
      setTimeout(() => {
        this.judgeLength()
      }, 100)
    },
    /**
     * 判断数组
     */
    judgeLength () {
      if (this.selectBox.tabConfig.items.length <= 1) {
        const el = this.$refs.selectTab.$children[0]
        el.$el.style.display = 'none'
      }
    },
    initTree (all, checked) {
      this.disable(all, checked)
      this.getInsideTreeData(all)
    },
    initList (all, checked) {
      this.leftList.items = all
      this.disable(all, checked)
      this.showList = true
    },
    /**
     * 左侧多选框改变
     */
    leftChange (data, event) {
      const arr = this.insideAllNode.filter(i => {
        if (data.some(x => x === i.id)) {
          return i
        }
      })
      this.rightList.items = this.rightList.items.concat(arr)
      const obj = {}
      this.rightList.items = this.rightList.items.reduce((cur, next) => {
        if (!obj[next.id]) {
          cur.push(next)
        }
        return cur
      }, [])
    },
    /**
     * 左侧列表改变
     */
    leftListChange (data, node) {
      if (!data) {
        this.rightList.items.splice(
          this.rightList.items.findIndex(i => i.id === node.id),
          1
        )
      } else {
        node[this.rightKey] = node[this.searchConfig.key]
        this.rightList.items.push(node)
      }
    },
    /**
     * 批量移除
     */
    removeCheck () {
      if (!this.showList) {
        this.removeTree()
      } else {
        this.removeList()
      }
      this.rightList.items = []
      this.rightList.default = []
      this.leftList.default = []
    },
    /**
     * 添加到 deleteList
     */

    removeList (removeArr) {
      this.leftList.default = []
    },
    removeTree (removeArr) {
      this.$refs.roleTree[this.index].setCheckedKeys([])
    },
    /**
     * 节点禁用函数
     */
    disabledFn (data, node) {
      if (this.rightList.items.filter(i => i.id === data.id).length !== 0) {
        return true
      }
      return false
    },
    /*
      单选删除
    */
    clickIcon (item) {
      this.rightList.items.splice(
        this.rightList.items.findIndex(i => i.id === item.id),
        1
      )
      this.leftList.default.splice(
        this.leftList.default.findIndex(i => i === item.id),
        1
      )
      this.rightList.default.splice(
        this.rightList.default.findIndex(i => i === item.id),
        1
      )
      if (!this.showList) {
        this.deleteTree(item)
      } else {
        this.deleteleftList(item)
      }
    },
    deleteleftList (item) {
      const arr = this.leftList.default
      arr.splice(arr.findIndex(i => i === item.id), 1)
    },
    deleteTree (item) {
      this.$nextTick(() => {
        this.$refs.roleTree[this.index].setChecked(item.id, false)
      })
    },
    /**
     * 左侧树状图选择
     */
    handleSelectionChange (data, status) {
      console.log('data', data)

      const checkedId = this.$refs.roleTree[this.index].getCheckedKeys()
      const allNode = [...this.allNode]
      const checkedNode = allNode.filter(
        i =>
          checkedId.some(x => x === i.id) &&
          i.type !== this.iconConfig.parentType.key
      )
      this.leftList.default = checkedNode.map(i => i.id)
      if (status) {
        this.rightList.items = this.rightList.items.concat(checkedNode)
        const obj = {}
        this.rightList.items = this.rightList.items.reduce((cur, next) => {
          obj[next.id] ? '' : (obj[next.id] = true && cur.push(next))
          return cur
        }, [])
      } else {
        this.rightList.items = this.rightList.items.filter(i =>
          checkedNode.some(x => x.id === i.id)
        )
      }
    },
    clear () {
      this.$refs.roleTree.setCheckedKeys([])
      this.disabled = true
    },
    /**
     * 节点禁用  取交集
     */
    disable (all, checked) {
      all.forEach(x => {
        if (checked.some(y => y.id === x.id)) {
          // x.disabled = true
          x.old = true
        }
      })
      this.rightList.items = all.filter(i => i.old)
    },
    /**
     * 获取树结构
     */
    getInsideTreeData (lists) {
      this.showList = false
      const temp = this.selectBox.tabConfig.items[this.index].treeConfig
      temp.expandedKeys = []
      this.selectBox.tabConfig.items[this.index].defaultProps = Object.assign(
        this.defaultProps,
        this.defaultPer
      )
      for (let i = lists.length - 1; i >= 0; i--) {
        // 添加图标
        if (lists[i].type === this.iconConfig.parentType.key) {
          lists[i].icon = this.iconConfig.parentType.icon
        } else {
          lists[i].icon = this.iconConfig.childrenType.icon
        }
      }
      temp.insideTreeData = this.GLOBAL.array.transToTreeData(lists)
      this.$nextTick(() => {
        const list_t = []
        if (this.insideChecked.length !== 0) {
          for (let i = 0; i < this.insideChecked.length; i++) {
            list_t.push(this.insideChecked[i].id)
          }
          temp.expandedKeys = [list_t[0]]
        } else {
          const expandedKeys = []
          this.getFirst(lists, expandedKeys)
          temp.expandedKeys = [temp.insideTreeData[0].id]
        }
        this.$refs.roleTree[this.index].setCheckedKeys(list_t)
      })
    },
    /*
      递归找第一个 type = 'permission'
    */
    getFirst (data, expandedKeys) {
      for (const i in data) {
        if (data[i]) {
          const node = data[i]
          if (node.type !== this.iconConfig.parentType.key) {
            expandedKeys.push(node)
            return
          } else if (node.children && node.children.length !== 0) {
            this.getFirst(node.children, expandedKeys)
          }
        }
      }
    },
    /**
     * 保存
     */
    save () {
      this.disabled = true
      this.addList = this.getAddList()
      this.deleteList = this.getdeleteList()
      this.searchConfig.params = {}
      this.$emit('save', this.addList, this.deleteList)
      this.$emit('callback', this.rightList.items.map(item => item.data || item))
    },
    closeDisabled () {
      this.disabled = false
    },
    getAddList () {
      const add = this.rightList.items.filter(i => !i.old).map(x => x.id)
      return add
    },
    getdeleteList () {
      const oldList = [...this.insideChecked]
      const newList = this.rightList.items.filter(i => i.old).map(x => x.id)
      const deleteList = oldList
        .filter(i => !newList.some(x => x === i.id))
        .map(z => z.id)
      return deleteList
    },
    /**
     * 取消
     */
    cancel () {
      this.searchConfig.params = {}
      this.$emit('close', false)
    },
    /**
      左侧树图标
    */
    renderContent (h, { node, data, store }) {
      return (
        <span class="treeSpan">
          <i class={data.icon}></i>
          <span> {node.label}</span>
        </span>
      )
    }
  }
}
</script>

<style lang="less">
li {
  margin: 0;
  padding: 0;
  list-style: none;
}
.selectBox {
  /* 滚动条滑块 */
  .tree-dialog::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 5px #dfe7f1;
    background: #dfe7f1;
  }
  .right-bottom::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 5px #dfe7f1;
    background: #dfe7f1;
  }
  li {
    margin: 0;
    padding: 0;
    list-style: none;
  }
  .vm-line {
    display: inline-block;
  }
  .box {
    overflow: hidden;
    height: 496px;
    border-bottom: 1px solid #dfe7f1;
    //左侧
    .left-box {
      overflow: hidden;
      height: 100%;
      width: 43%;
      float: left;
      border-right: 1px solid #dfe7f1;
      .left-top {
        height: 67px;
        padding: 0 23px 0 20px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .left-bottom {
        padding: 0 0 0 17px;
        height: 100%;
        .el-tabs__item {
          line-height: 19px;
          height: 27px;
        }
      }
    }
    // 右侧
    .right-box {
      width: calc(57% - 1px);
      .right-top {
        text-align: left;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 58px;
        width: 100%;
        .top-box {
          width: 100%;
          margin: 0px 20px;
          height: 100%;
          text-align: left;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
      .right-bottom {
        height: calc(100% - 57px);
        .icon-right {
          text-align: right;
          width: 80px;
          i {
            height: 18px;
            width: 18px;
            font-size: 18px;
            padding-right: 18px;
          }
          .el-icon-circle-close {
            cursor: pointer;
            &:hover {
              color: rgb(170, 207, 255);
            }
          }
        }
      }
    }
    .checkbox {
      overflow: hidden;
      margin-top: -10px;
      padding: 0 20px 0 0;
      .checkBox-box {
        text-align: left;
        display: block;
        color: #606266;
        font-weight: 500;
        font-size: 14px;
        display: inline-block;
        width: 100%;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
        user-select: none;
        margin: 10px 0 0px 20px;
        .vc-icon {
          margin-right: 15px;
        }
        .icon-right {
          float: right;
        }
        .valueBox {
          width: 180px;
          display: inline-block;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          line-height: 14px;
        }
      }
    }
  }
  .treeSpan {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .vm-line {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  //定义tab
  .button-small () {
    padding: 7px 20px;
    font-size: 14px;
  }
  .el-tabs--top {
    height: 100%;
    margin-top: -20px;
  }

  .el-tabs__content {
    height: 100%;
  }
  .icon-left {
    width: 210px;
  }
}
// 弹出框样式2—为了匹配展示tree的样式。_cdw
.tree-dialog-form {
  .el-tabs__nav-scroll {
    padding: 0 23px;
  }
  display: flex;
  justify-content: center;
  align-items: center;
  .el-dialog {
    height: 607px;
    .el-dialog__footer {
      margin-left: 15px !important;
    }
    .el-dialog__header {
      height: 24px;
      border-bottom: 1px solid #dfe7f1;
      padding: 10px 17px;
      .el-dialog__headerbtn {
        top: auto;
      }
    }
    margin: 0 !important;
    border-radius: 5px;
    .el-dialog__title {
      width: 64px;
      height: 21px;
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      line-height: 21px;
      color: rgba(68, 68, 68, 1);
      opacity: 1;
    }
    .el-dialog__body {
      height: calc(100% - 70px);

      padding: 0;
      .el-form {
        height: 100%;
        padding-bottom: 2px;
        .el-form-item .show-password .el-input__inner {
          padding-right: 50px;
        }
      }
    }
    .el-dialog__footer {
      text-align: right;
    }
  }

  &.append-to-body {
    font-family: 'Microsoft YaHei';
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #2c3e50;
    .el-dialog__header {
      text-align: left !important;
    }
    .el-main {
      min-height: 200px;
      padding: 0;
    }
  }
}
.el-dialog__header {
  text-align: left !important;
}
// 弹出框中展示树_cdw
.tree-dialog {
  width: 237px;
  height: 100%;
  margin-right: 0px;
  .org-tree {
    width: 100%;
    display: inline-block !important;
    .el-tree-node__content {
      height: 34px;
      line-height: 34px;
      padding-right: 5px;
    }
  }
}
</style>
